package com.campus.client.view;

import com.campus.client.controller.StudentCourseController;
import com.campus.common.vo.User;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class StudentCourseFrame {

    private Button btnLogout;
    private StudentCourseController controller;

    private User user = new User();
    public User getUser() { return user; }
    public void setUser(String Id, String password, String role) {
        this.user.setId(Id);
        this.user.setPassword(password);
        this.user.setRole(role);
    }

    public void start(Stage primaryStage) throws Exception {

        // 主布局：BorderPane
        BorderPane root = new BorderPane();

        // 顶部工具栏
        ImageView logoView = new ImageView(new Image(getClass().getResource("/badge.png").toExternalForm()));
        logoView.setFitHeight(40);
        logoView.setPreserveRatio(true);

        Label lblTitleCN = new Label("选课");
        lblTitleCN.setStyle("-fx-text-fill: white; -fx-font-size: 18px; -fx-font-weight: bold;");
        Label lblTitleEN = new Label("Course Selection");
        lblTitleEN.setStyle("-fx-text-fill: white; -fx-font-size: 12px;");

        VBox titleBox = new VBox(2, lblTitleCN, lblTitleEN);
        titleBox.setAlignment(Pos.CENTER_LEFT);

        HBox logoAndTitle = new HBox(8, logoView, titleBox);
        logoAndTitle.setAlignment(Pos.CENTER_LEFT);

        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);

        Label lblRole = new Label("当前身份：学生");
        lblRole.setStyle("-fx-text-fill: white; -fx-font-size: 12px; -fx-font-weight: bold;");

        Image logoutImg = new Image(getClass().getResource("/logout.png").toExternalForm());
        ImageView logoutIcon = new ImageView(logoutImg);
        logoutIcon.setFitHeight(14);
        logoutIcon.setPreserveRatio(true);

        btnLogout = new Button("退出选课", logoutIcon);
        btnLogout.getStyleClass().add("logout-button");
        btnLogout.setOnAction(e -> {
            try { back(); }
            catch (IOException ex) { throw new RuntimeException(ex); }
        });

        HBox topBar = new HBox(15, logoAndTitle, spacer, lblRole, btnLogout);
        topBar.setPadding(new Insets(6));
        topBar.setStyle("-fx-background-color: #3b7bc3;");
        topBar.setAlignment(Pos.CENTER_LEFT);

        root.setTop(topBar);

        // 左侧侧边栏
        VBox sidebar = new VBox(0);
        sidebar.setPadding(new Insets(15,0,15,0));
        sidebar.setStyle("-fx-background-color: #3b7bc3");

        SidebarButton btnRetake = new SidebarButton("重修选课");
        SidebarButton btnFirstTime = new SidebarButton("首修选课");
        SidebarButton btnAll = new SidebarButton("所有课程");
        SidebarButton btnSelected = new SidebarButton("已选课程");
        SidebarButton btnViewSchedule = new SidebarButton("查看课表"); // 暂未实现

        List<SidebarButton> buttons = Arrays.asList(btnRetake, btnFirstTime, btnAll, btnSelected, btnViewSchedule);

        for (SidebarButton btn : buttons) {
            btn.setPrefHeight(50);         // 高度
            btn.setMaxWidth(Double.MAX_VALUE);
        }

        sidebar.getChildren().addAll(buttons);
        root.setLeft(sidebar);

        // 中间内容区域
        BorderPane contentArea = new BorderPane();

        // 顶部搜索栏
        HBox searchBar = new HBox(10);
        searchBar.setPadding(new Insets(10));
        searchBar.setAlignment(Pos.CENTER_LEFT);

        TextField searchField = new TextField();
        searchField.setPromptText("输入课程编号和名称");
        searchField.setPrefWidth(300);

        Button searchBtn = new Button("🔍 查询");
        searchBtn.setStyle("-fx-background-color: #3b7bc3; -fx-text-fill: white; -fx-font-weight: bold;");
        searchBtn.setOnAction(e -> {
            String keyword = searchField.getText().trim();
            if (keyword.isEmpty()) {
                StudentCourseView cv = new StudentCourseView(StudentCourseView.CourseViewMode.SELECTABLE, user);
                contentArea.setCenter(cv.getView());
            } else {
                StudentCourseView cv = new StudentCourseView(StudentCourseView.CourseViewMode.QUERY, keyword, user);
                contentArea.setCenter(cv.getView());
            }
        });

        searchBar.getChildren().addAll(searchField, searchBtn);
        contentArea.setTop(searchBar);

        // 默认显示首修选课
        StudentCourseView defaultView = new StudentCourseView(StudentCourseView.CourseViewMode.FIRST_TIME, user);
        contentArea.setCenter(defaultView.getView());

        root.setCenter(contentArea);

        // 按钮列表，用于更新选中状态
        List<SidebarButton> sidebarButtons = Arrays.asList(btnRetake, btnFirstTime, btnAll, btnSelected, btnViewSchedule);

        // 点击事件绑定
        btnRetake.setOnAction(e -> {
            StudentCourseView cv = new StudentCourseView(StudentCourseView.CourseViewMode.RETAKE, user);
            contentArea.setCenter(cv.getView());
            updateSidebarSelection(sidebarButtons, btnRetake);
        });

        btnFirstTime.setOnAction(e -> {
            StudentCourseView cv = new StudentCourseView(StudentCourseView.CourseViewMode.FIRST_TIME, user);
            contentArea.setCenter(cv.getView());
            updateSidebarSelection(sidebarButtons, btnFirstTime);
        });

        btnAll.setOnAction(e -> {
            StudentCourseView cv = new StudentCourseView(StudentCourseView.CourseViewMode.ALL, user);
            contentArea.setCenter(cv.getView());
            updateSidebarSelection(sidebarButtons, btnAll);
        });

        btnSelected.setOnAction(e -> {
            StudentCourseView cv = new StudentCourseView(StudentCourseView.CourseViewMode.SELECTED, user);
            contentArea.setCenter(cv.getView());
            updateSidebarSelection(sidebarButtons, btnSelected);
        });

        btnViewSchedule.setOnAction(e -> {
            // TODO: 实现查看课表功能
            System.out.println("查看课表功能尚未实现");
            updateSidebarSelection(sidebarButtons, btnViewSchedule);
        });

        updateSidebarSelection(sidebarButtons, btnFirstTime);

        // 场景和样式
        Scene scene = new Scene(root, 900, 600);
        scene.getStylesheets().add(getClass().getResource("/CourseView.css").toExternalForm());

        primaryStage.setTitle("学生端选课系统 - 简易版");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void back() throws IOException {
        Stage stage = (Stage) btnLogout.getScene().getWindow();
        StudentMainFrame studentMainFrame = new StudentMainFrame();
        studentMainFrame.setUser(user.getId(),user.getPassword(),user.getRole());
        studentMainFrame.setUser(user.getId(), user.getPassword(), user.getRole());
        Stage newStage = new Stage();
        studentMainFrame.show(newStage);
        stage.close();
    }

    private void updateSidebarSelection(List<SidebarButton> buttons, SidebarButton selected) {
        for (SidebarButton btn : buttons) {
            btn.setSelected(false);
        }
        selected.setSelected(true);
    }
}
